package com.mokairui.search;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description
 * @Author Mokairui
 * @Since 2021/11/1
 */
@Slf4j
public class BinarySearch {
    public static void main(String[] args) {
        int[] array = {1, 5, 8, 11, 19, 22, 31, 35, 40, 45, 48, 49, 50};
        int target = 48;
        int idx = binarySearch(array, target);
        System.out.println(idx);
    }

    // 二分查找, 找到返回元素索引, 找不到返回 -1
    private static int binarySearch(int[] array, int target) {
        int start = 0;
        int end = array.length - 1;
        int mid;
        while (start <= end) {
            // 处理溢出方式一
//            mid = start + (end - start) / 2;
            // 处理溢出方式二 效率更好 右移一位等于正数除2
            mid = (start + end) >>> 1;
            if (array[mid] == target) {
                return mid;
            } else if (array[mid] < target) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }
        return -1;
    }
}
